package il.technion.cs236369.webserver.examples;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XPathExample {

	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		docFactory.setNamespaceAware(true);
		DocumentBuilder builder = docFactory.newDocumentBuilder();
		Document doc = builder.parse("config.xml");
		
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();
		
		// running a simple query
		System.out.println(xpath.compile("//server-config/@base").evaluate(doc));
		
		// running a nested query
		NodeList nl = (NodeList) xpath.compile("//multi").evaluate(doc, XPathConstants.NODESET);
		for (int i=0; i < nl.getLength(); ++i) {
			System.out.println(xpath.compile("./text()").evaluate(nl.item(i)));
		}
	}
}
